package com.music.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.music.R;
import com.music.adapter.MusicListAdapter;
import com.music.utilbean.Constant;
import com.music.utilbean.KuwoApplication;
import com.music.utilbean.MediaUtils;
import com.music.utilbean.Mp3Info;
import com.music.utilbean.ToUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * 本地歌曲列表，底部的播放状态栏
 */
@SuppressLint("NewApi")
public class LocalMusicActivity extends MusicBaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
	private boolean               mIsResume;
	private ImageView             localMusicBack;
	private ListView              mMusicListLv;
	private ArrayList<Mp3Info>    mp3Infos;
	private MusicListAdapter      musicListAdapter;
	private TextView              mTvNothing;
	//	private NewCallReceiver       mCallReceiver;
	private WakeBroadcastReceiver mReceiver1;
	private View                  mBtm_linear;
	private int                   mPosition;
	private ImageView             image_cd, img_go, img_back, img_begin;
	private TextView textmusic, textsinger;
	private static SharedPreferences sp;
	private final Handler mHandler = new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_local_music);
		//绑定服务
//		bindplayService();
		initView();
		sp = getSharedPreferences(Constant.SP_NAME, Context.MODE_PRIVATE);
		loadData();

		//注册关于唤醒机器人的广播
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.WAKEUPFILTER);
		filter.addAction(Constant.MUSICPLAYFILTER);

		mReceiver1 = new WakeBroadcastReceiver(LocalMusicActivity.this);
		registerReceiver(mReceiver1, filter);

		//注册来电接收者,监听来电状态，如果来电话了，就退出playActivity
		//		IntentFilter callFilter = new IntentFilter(EMClient.getInstance().callManager().getIncomingCallBroadcastAction());
		//		if (mCallReceiver == null) {
		//			mCallReceiver = new NewCallReceiver();
		//		}
		//		registerReceiver(mCallReceiver, callFilter);

		//注册eventbus订阅者
		//		EventBus.getDefault().register(LocalMusicActivity.this);

		String stringExtra = getIntent().getStringExtra(Constant.INTENTPLAYMUSIC);

		//用户说唱首歌等语音命令，就会调用下面的代码，从intent中取出key，然后播放音乐
		if (stringExtra != null && stringExtra.equals(Constant.INTENTPLAYMUSIC)) {
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					if (playService != null) {
						if (playService.ispause()) {//当点击播放按钮时,如果是暂停状态就继续播放
							img_begin.setImageResource(R.drawable.pause);
							playService.start();
						} else {
							playService.play(sp.getInt("currentposition", playService.getCurrentPosition()));
						}
					}
				}
			}, 2000);

		}
	}


	/**
	 * 机器人被唤醒时会触发下面的广播接收者
	 */
	private static class WakeBroadcastReceiver extends BroadcastReceiver {

		private final WeakReference<LocalMusicActivity> mContext;

		public WakeBroadcastReceiver(LocalMusicActivity context) {
			mContext = new WeakReference<>(context);
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			LocalMusicActivity activity = mContext.get();
			if (activity != null) {
				String action = intent.getAction();
				if (Constant.WAKEUPFILTER.equals(action)) {
					KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
					if (event.getKeyCode() == KeyEvent.KEYCODE_NOTIFICATION && event.getAction() == KeyEvent.ACTION_UP) {
						activity.stopPlay();
						//activity.mHandler.postDelayed(new Runnable() {
						//	@Override
						//	public void run() {
						//		//finish
						//	}
						//}, 1000);
						activity.finish();
					}
				} else if (Constant.MUSICPLAYFILTER.equals(action)) {//如果是远程播放歌曲的广播
					activity.remotePlayMusic(intent);
				}
			}
		}
	}


	//广播接收者，接收到广播就暂停播放音乐退出此activity
	//	private class NewCallReceiver extends BroadcastReceiver {
	//		@Override
	//		public void onReceive(Context context, Intent intent) {
	//			if (!DemoHelper.getInstance().isLoggedIn()) {
	//				return;
	//			}
	//			finish();
	//		}
	//	}

	/**
	 * 机器人被远程控制播放音乐
	 */
	private void remotePlayMusic(final Intent intent) {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				String stringExtra = intent.getStringExtra(Constant.SONGNAME);
				if (!TextUtils.isEmpty(stringExtra)) {
					String[] split = stringExtra.split(",");
					mPosition = Integer.parseInt(split[1]);
					if (playService != null) {
						playService.play(mPosition);
						changeUIstateOnplay(mPosition);
					}
				}
			}
		}, 1000);
	}

	private void initView() {
		localMusicBack = (ImageView) findViewById(R.id.localMusicBack);
		mMusicListLv = (ListView) findViewById(R.id.listview_mymusic);
		image_cd = (ImageView) findViewById(R.id.image_cd);
		img_back = (ImageView) findViewById(R.id.imageButton_back);
		img_begin = (ImageView) findViewById(R.id.imageButton_begin);
		img_go = (ImageView) findViewById(R.id.imageButton_go);
		textmusic = (TextView) findViewById(R.id.textmusic);
		textsinger = (TextView) findViewById(R.id.textsinger);
		mTvNothing = (TextView) findViewById(R.id.tvNothing);
		mBtm_linear = findViewById(R.id.btm_linear);

		mBtm_linear.setOnClickListener(this);
		mMusicListLv.setOnItemClickListener(this);
		img_begin.setOnClickListener(this);
		img_back.setOnClickListener(this);
		img_go.setOnClickListener(this);
		image_cd.setOnClickListener(this);
		localMusicBack.setOnClickListener(this);

		mMusicListLv.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
			@Override
			public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
				menu.setHeaderTitle("选择操作");
				menu.add(0, 0, 0, "删除");
				menu.add(0, 1, 0, "取消");
			}
		});
	}


	private void loadData() {//加载本地音乐列表
		mp3Infos = MediaUtils.getMp3Infos(LocalMusicActivity.this);
		if (musicListAdapter == null) {
			musicListAdapter = new MusicListAdapter(LocalMusicActivity.this, mp3Infos);
		}

		musicListAdapter.notifyDataSetChanged();
		mMusicListLv.setAdapter(musicListAdapter);

		//		StringBuffer sb = new StringBuffer();
		//		sb.append(Constant.SONGLIST + ",");
		//		for (int i = 0; i < mp3Infos.size(); i++) {
		//			sb.append(mp3Infos.get(i).getTitle() + ",");
		//		}
		//发送透传消息，把歌曲列表发送到手机端，为实现遥控歌曲播放做铺垫
		//把aaaa的歌曲列表发送给bbbb
		//		EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
		//		String currentUser = EMClient.getInstance().getCurrentUser();
		//		//Todo 下面的代码应该改成 识别设备型号如果是woosiyuan001就return掉。
		//		if (currentUser.equals("bbbb") || currentUser.equals("cccc")) {
		//			return;
		//		}
		//
		//		EMCmdMessageBody cmdBody = new EMCmdMessageBody(sb.toString());
		//		//Todo 应该改成给每一位好友都发一次透传消息
		//		cmdMsg.setTo("bbbb");
		//		//		cmdMsg.setTo("cccc");
		//		cmdMsg.addBody(cmdBody);
		//		EMClient.getInstance().chatManager().sendMessage(cmdMsg);
	}

	@Override
	public void publish(int progress) {
		//更新进度
	}

	//给菜单项添加事件
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		//info.id得到listview中选择的条目绑定的id
		String id = String.valueOf(info.id);
		switch (item.getItemId()) {
			case 0:
				Log.i("bb", id);
				//删除歌曲（1、根据Id删除歌曲文件 2、删除媒体库的记录）
				deletemusic(LocalMusicActivity.this, Integer.parseInt(id));
				return true;
			default:
				return super.onContextItemSelected(item);
		}
	}

	//删除歌曲
	public void deletemusic(Context context, int index) {
		mp3Infos = MediaUtils.getMp3Infos(LocalMusicActivity.this);

		long id = mp3Infos.get(index).getId();

		Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,
				MediaStore.Audio.Media._ID + "=" + id, null,
				MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
		String url = null;
		if (cursor.moveToNext()) {
			url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
		}

		//第一步删文件
		System.out.println(url);
		File musicfile = new File(url);
		if (musicfile.exists()) {
			musicfile.delete();
			Toast.makeText(context, "文件删除成功", Toast.LENGTH_SHORT).show();
		} else {
			ToUtil.showShort(getApplicationContext(), "文件不存在");
		}
		//第二步删记录
		ContentResolver resolver = context.getContentResolver();
		resolver.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MediaStore.Audio.Media._ID + "=?", new String[]{id + ""});
		ToUtil.showShort(getApplicationContext(), "记录删除成功");
		String path = Environment.getExternalStorageDirectory().getAbsolutePath();
		MediaScannerConnection.scanFile(LocalMusicActivity.this, new String[]{path}, null, null);
		loadData();
	}


	@SuppressLint("NewApi")
	@Override
	public void change(int position) {
		//切换播放位置
		changeUIstateOnplay(position);
	}

	//回调播放状态下的UI设置
	public void changeUIstateOnplay(int position) {
		if (mp3Infos.size() <= 0) {
			mTvNothing.setVisibility(View.VISIBLE);
			return;
		}
		if (position >= 0 && position <= mp3Infos.size()) {
			mTvNothing.setVisibility(View.INVISIBLE);
			Mp3Info mp3Info = mp3Infos.get(position);
			textmusic.setText(mp3Info.getTitle());
			Log.e("LocalMusicActivity", "changeUIstateOnplay: " + mp3Info.getTitle());
			textsinger.setText(mp3Info.getArtist());
			Bitmap albumBitmap = MediaUtils.getArtwork(LocalMusicActivity.this, mp3Info.getId(), mp3Info.getAlbumId(), true, true);
			image_cd.setImageBitmap(albumBitmap);
			if (playService.isplaying()) {
				img_begin.setImageResource(R.drawable.pause);
			} else {
				img_begin.setImageResource(R.drawable.begin);
			}
		}
	}

	public void stopPlay() {//停止播放歌曲
		if (playService.isplaying()) {
			img_begin.setImageResource(R.drawable.begin);
			playService.pause();
		}
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.localMusicBack) {//当点击左上角返回键时
			LocalMusicActivity.this.finish();
			playService.pause();
			//退出LocalMusicActivity页面时关闭状态灯
			//			DemoHelper.getInstance().closeLedLight();
		}

		if (v.getId() == R.id.imageButton_begin) {//当点击播放按钮时
			if (playService.isplaying()) {//当点击播放按钮时,如果正在播放音乐就暂停
				img_begin.setImageResource(R.drawable.begin);
				playService.pause();
			} else {
				if (playService.ispause()) {//当点击播放按钮时,如果是暂停状态就继续播放
					img_begin.setImageResource(R.drawable.pause);
					playService.start();
				} else {
					//这个方法里有打开状态灯的代码
					playService.play(sp.getInt("currentposition", playService.getCurrentPosition()));
				}
			}
		} else if (v.getId() == R.id.imageButton_back) {//点击上一曲按钮时
			playService.prev();
			img_begin.setImageResource(R.drawable.pause);
		} else if (v.getId() == R.id.imageButton_go) {//点击下一曲按钮时
			playService.next();
			img_begin.setImageResource(R.drawable.pause);
		} else if (v.getId() == R.id.image_cd) {//点击cd唱片时
			Intent intent = new Intent(LocalMusicActivity.this, MusicPlayerActivity.class);
			startActivity(intent);
		} else if (v.getId() == R.id.btm_linear) {
			Intent intent1 = new Intent(LocalMusicActivity.this, MusicPlayerActivity.class);
			startActivity(intent1);
		}
	}

	//音乐列表的条目被点击时，出发下面的点击事件
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Intent intent = new Intent(LocalMusicActivity.this, MusicPlayerActivity.class);
		startActivity(intent);
		//changeUIstateOnplay(position);
		Log.e("LocalMusicActivity", "onItemClick: " + "位置position" + position);

		//EventBus.getDefault().post(mp3Infos.get(position));
		if (playService.isplaying()) {
			//playService.pause();
		}
		playService.play(position);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mIsResume = true;
		bindplayService();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mIsResume = false;
		unbindplayService();
	}

	//当playService中出现播放下一曲，上一曲的事件时，eventbus会把正在播放的歌曲传递到这边来，在下面的方法中更新UI
	//	@Subscribe(threadMode = ThreadMode.MAIN)
	//	public void onMusicChanged(Mp3Info mp3Info) {
	//		textmusic.setText(mp3Info.getTitle());
	//		Log.e("LocalMusicActivity11", "onMusicChanged: " + mp3Info.getTitle());
	//		textsinger.setText(mp3Info.getArtist());
	//		Bitmap albumBitmap = MediaUtils.getArtwork(LocalMusicActivity.this, mp3Info.getId(), mp3Info.getAlbumId(), true, true);
	//		image_cd.setImageBitmap(albumBitmap);
	//		if (playService.isplaying()) {
	//			img_begin.setImageResource(R.drawable.pause);
	//		} else {
	//			img_begin.setImageResource(R.drawable.begin);
	//		}
	//	}

	@Override
	protected void onDestroy() {
		//注销唤醒的广播
		unregisterReceiver(mReceiver1);
		//注销来电监听的广播
		//		unregisterReceiver(mCallReceiver);
		//activity销毁时
		super.onDestroy();

		//解除绑定播放服务
//		unbindplayService();

		//保存当前播放的一些状态值
		KuwoApplication application = (KuwoApplication) getApplication();
		SharedPreferences.Editor editor = application.sharedPreferences.edit();
		editor.putInt("currentposition", playService.getCurrentPosition());
		editor.putInt("play_mode", playService.getPlay_mode());
		editor.apply();
		playService.pause();

		//注销eventbus订阅事件
		//		EventBus.getDefault().unregister(LocalMusicActivity.this);
	}

}
